<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     Pagizer
 * @subpackage  backoffice
 */

/**
 * Service to display the context menu
 */
class m_backoffice_services_ContextMenuService extends f_core_Service
{
	private static $instance;
	
	/**
	 * @return m_backoffice_services_MenuService
	 */
	private function __construct()
	{
		return $this;
	}
	
	/**
	 * Get singleton instance
	 *
	 * @return m_backoffice_services_MenuService
	 */
	public static function getInstance()
	{
		if(self::$instance === null)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
		
	/**
	 * Get context menu items associated to a document by his id
	 * @param $document
	 * @return unknown_type
	 */
	public function getContextMenuItems(f_document_BaseDocument $document)
	{
		$elements = $this->getDocumentContextMenuItems($document);
		
		if(is_null($elements))
		{
			return array();
		}
		else
		{
			return $this->getItemsArrayFromXmlElements($document, $elements);			
		}
	}
	
	public function getRightClickItems(f_document_BaseDocument $document)
	{
		if($document->getDocumentModel() == "modules_backoffice/rootNode")
		{
			return null;
		}
		else
		{
			$items = array();

			if($document->isLocalized())
			{
				$original = $document->getVoDocument();
				
				if($original->getDocumentModel() == "modules_website/website")
				{
					$rootNode = $original;
				}
				else
				{
					$rootNodes = f_relation_ManagerNew::getInstance($original)->getParents()->withModel("website/website")->withLang($original->getLang())->retrieveDocuments();
					$rootNode = end($rootNodes);					
				}				

				if($rootNode == false)
				{
					return null;
				}
				
				foreach($rootNode->getAllLangs() as $lang)
				{
					if($lang != $document->getLang())
					{
						$translatedDocument = $document->getTranslation($lang);
						if($translatedDocument->isTranslated())
						{
							$item["label"] = $lang." / ".$translatedDocument->getLabel();
							$item["icon"] = $translatedDocument->getIcon();
							$item["href"] = $translatedDocument->getEditUrl($lang);
						}
						else
						{
							$item["label"] = $lang." / ".$document->getLabel();
							$item["icon"] = "message_add.png";
							$item["href"] = $translatedDocument->getEditUrl($lang);
						}

						$items[] = $item;
					}
				}

				if(method_exists($original, "getWebsiteId"))
				{
					$item["label"] = "Ajouter une langue au site";
					$item["icon"] = "message_add.png";
					$item["href"] = f_core_Routing::getUrl("translateWebsite", array("docId" => $original->getWebsiteId()));
					$item["class"] = "nyroModal";
					$items[] = $item;					
				}
				else if($document->getDocumentModel() == "modules_website/website")
				{
					$item["label"] = "Ajouter une langue au site";
					$item["icon"] = "message_add.png";
					$item["href"] = f_core_Routing::getUrl("translateWebsite", array("docId" => $document->getUniqueId()));
					$item["class"] = "nyroModal";
					$items[] = $item;
				}				
			}
			
			if(count($items) > 0)
			{
				return $items;				
			}
			return null;
		}
	}
	
	/**
	 * Get the context actions menu for a given document 
	 * 
	 * @param integer $documentId
	 * @return string
	 */
	private function getDocumentContextMenuItems(f_document_BaseDocument $document)
	{					
		$docModel = substr($document->getDocumentModel(),8);		
		list($module, $documentName) = explode("/", $docModel);

        if($document->getModel() == 'modules_website/website')
        {
            $module = $document->getConfigModule();
        }
        else
        {
            if($module == "backoffice")
            {
                $module = $document->getModule();
            }
        }
		
		return $this->getXmlElements($module, $documentName);			
	}
	
	/**
	 * Get the context actions menu for a given root node 
	 * 
	 * @param $rootNode m_backoffice_documents_RootNode
	 * @return unknown_type
	 */
	private function getRootNodeContextMenuItems(m_backoffice_documents_RootNode $rootNode)
	{				
		return $this->getXmlElements($rootNode->getModule(), "rootNode");
	}
	
	/**
	 * Get XML items declared for a given module and model
	 * @param $module
	 * @param $documentModel
	 * @return null|array f_xml_XmlElement
	 */
	private function getXmlElements($module, $documentModel)
	{
		$xmlFile = MODULES_DIR.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR."config".DIRECTORY_SEPARATOR."contextMenu".DIRECTORY_SEPARATOR.$documentModel.".xml";
	
		if(is_file($xmlFile))
		{
			$elements =  f_xml_Xpath::getInstance($xmlFile)->getElementsFromXpath("item");

			if(is_array($elements) && count($elements) > 0)
			{
				return $elements;
			}
		}
		
		return null;
	}
	
	/**
	 * Retrieve a formatted array from xml elements
	 * @param $document
	 * @param $xmlElements
	 * @return array
	 */
	private function getItemsArrayFromXmlElements($document, $xmlElements)
	{		
		$items = array();

        if($document->getModel() == 'modules_website/website')
        {
            $module = $document->getConfigModule();
        }
        else
        {
            $docModel = substr($document->getDocumentModel(),8);
            list($module, $documentName) = explode("/", $docModel);

            if($module == "backoffice")
            {
                $module = $document->getModule();
            }
        }
	
		foreach($xmlElements as $xmlElement)
		{
            $right = $xmlElement->getAttributeValue('right');
			$item["icon"] = $xmlElement->getAttributeValue('icon');
			$item["label"] = $xmlElement->getAttributeValue('label');
            $item["type"] = $xmlElement->getAttributeValue('type');
			$item["href"] = f_core_Routing::getUrl($xmlElement->getAttributeValue('route'), array("docLang" => strtolower($document->getLang()), "docId" => $document->getUniqueId(), "configModule" => $module));
			$item["tooltip"] = $xmlElement->getAttributeValue('tooltip');

            if(!is_null($right))
            {
                $userContext = f_context_User::getInstance();
                $user = $userContext->getUser();

                if(!$userContext->hasRight($module.'_'.$right) || !$user->hasDocRight($document, $module, strtolower($right)))
                {
                    continue;
                }
            }

            $items[] = $item;
		}
		
		return $items;
	}
}